/*  Copyright © 2009 Blake Hegerle -*- C++ -*- */

/*  This file is part of metal.
 
    Metal is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see
    <http://www.gnu.org/licenses/>.

*/

#pragma once

#include "forward.h"
#include "def.h"
#include "util.h"
#include "expr_impl.h"
#include "imbue_type.h"
#include "type_code.h"
#include "function_detail.h"

namespace metal {
  template<typename Proto, typename MetaExpr>
  struct function { };

  class function_impl {
    typedef std::vector<param_impl> params_t;
    typedef params_t::const_iterator const_iterator;
  public:
    template<typename I>
    function_impl(type_ptr type,
		  const std::string &name, 
		  const expr_ptr &body, 
		  I params)
      : t(type), n(name), b(body), params(params) {}

    type_ptr type() const { return t; }
    const std::string &name() const { return n; }
    expr_ptr body() const { return b; }
    const_iterator begin() const { return params.begin(); }
    const_iterator end() const { return params.end(); }
  private:
    std::string n;
    expr_ptr b;
    params_t params;
    type_ptr t;
  };

  template<
    typename Scope,
    typename ReturnType,
    typename Ident,
    typename Type,
    typename MetaExpr,
    typename... Params
    >
  function_ptr
  convert(const assignment<true, Ident, meta::lambda_expr<Type, MetaExpr, Params...> > &def) {
    using namespace meta;

    std::vector<param_impl> params;
    function_detail::meta_param<Params...>::lower(params);
 
    auto body = imbue_type<MetaExpr, Scope>(def.impl()->expr());
    auto f = new function_impl(lower<ReturnType>(), 
			       name_of<Ident>(), 
			       body, 
			       params);
    return function_ptr(f);
  }
}
